﻿/*
*类名：ImageMessageDeal
*归属：QinMing.Weixin.MessageHandlerImage命名空间
*用途：处理微信用户发给公众号的图片消息，并给予微信用户处理结果通知，通过微信服务器转发给微信用户
*作者：乱世刀疤
*日期：2020.05.02
*/

using System;
using System.Web;
using System.Xml;
using System.Text;
using System.IO;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Drawing.Imaging;
using System.Net;
using QinMing.Config;
using QinMing.Weixin.ReturnContent;
using QinMing.WeixinContainer;
using QinMing.Tools;

namespace QinMing.Weixin.MessageHandlerImage
{
	//图片消息处理
    public class ImageMessageDeal :System.Web.UI.Page
    {

		public string DealResult(string weixinXML)
        {
            string content = DealImage(weixinXML);  
            return content;
        }
        
        public string DealImage(string weixinXML)
        {
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(weixinXML);
            XmlNodeList list = doc.GetElementsByTagName("xml");
            XmlNode xn = list[0];
            string FromUserName = xn.SelectSingleNode("//FromUserName").InnerText;   //关注用户的加密后openid
            string ToUserName = xn.SelectSingleNode("//ToUserName").InnerText;       //公众微信号原始ID
            string MsgType = xn.SelectSingleNode("//MsgType").InnerText;
            string PicUrl = xn.SelectSingleNode("//PicUrl").InnerText.ToString().Trim();
			string MediaId = xn.SelectSingleNode("//MediaId").InnerText.ToString().Trim();
			string MsgId = xn.SelectSingleNode("//MsgId").InnerText;
            string strresponse = "";

			//保存图片信息
			SaveImage(FromUserName, ToUserName, PicUrl, MediaId, MsgId);
			
			//给用户发来的图片右下角加国旗，生成新图片链接
			string ResultPicUrl = AddNationalFlag(PicUrl, FromUserName, MediaId);
			
			//引用QinMing.Weixin.ReturnContent命名空间下的ReturnMsg类来生成固定格式的回应消息
			ReturnMsg rm = new ReturnMsg();
			strresponse = rm.ReturnText(FromUserName, ToUserName, "<a href='" + ResultPicUrl + "'>点击这里获取你的新头像</a>");
			//strresponse = rm.ReturnTuWen(FromUserName, ToUserName, "发送图片测试", "用户发送图片测试", imgurl, "your url");
			
			//告知客服人员有新的留言，或者启动客服消息管理工单流程
			QinMing.WeixinTemplateMessage.SendTemplateMessage.SendRemindMsg("管理员openid", "客户发送图片：" + PicUrl, "");  
			
            return strresponse; 
        }
		
		//把用户发的图片信息保存到数据表表中
		public void SaveImage(string FromUserName, string ToUserName, string PicUrl, string MediaId, string MsgId)
		{
            SqlConnection conn = new SqlConnection(QinMingConfig.DatabaseConnStr);
            conn.Open();
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = conn;
			
			cmd.CommandText = "insert into weixin_recv_msg (msg_type,msg_id,open_id,gh_id,recv_time,pic_url,media_id) values("
			    + "'image','" + MsgId + "','" + FromUserName + "','" + ToUserName + "',getdate(),'" + PicUrl + "','" + MediaId + "')";
            cmd.ExecuteScalar();
			
            if (conn.State == ConnectionState.Open)
            {
                conn.Close();
                conn.Dispose();
            }
		}
		
		//给图片右下角加国旗
		public string AddNationalFlag(string PicUrl,string FromUserName, string MediaId)
		{
			string imgurl = "";
			string TmpDir = "E:\\web目录\\Images\\Src\\";
			string TmpFileName = FromUserName + DateTime.Now.Ticks.ToString() + ".jpg";
			
			//使用PicUrl下载用户发送的图片到服务器，为使代码简短，没有增加后缀名判断
			//System.Net.WebClient webClient = new System.Net.WebClient();
			//webClient.DownloadFile(PicUrl, TmpDir + TmpFileName);
			
			//使用MediaId下载用户发送的图片到服务器
			DownloadFileByMediaId(TmpDir + TmpFileName, MediaId);

			//读取用户发送的图片，待添加国旗国标
			Bitmap srcImg = new Bitmap(TmpDir + TmpFileName);
			Graphics graphics = Graphics.FromImage(srcImg);

			//给图片指定位置添加国旗
			int flagSize = (int)Math.Min(srcImg.Width * 0.20f, srcImg.Height * 0.20f);  //国旗图标是方形的，透明背景，高度取微信用户发送图片长、宽最小值的25%
			System.Drawing.Image guoqi = System.Drawing.Image.FromFile(TmpDir + "guoqi1.png");
			graphics.DrawImage(guoqi, srcImg.Width - flagSize - 8, srcImg.Height - flagSize - 8, flagSize, flagSize);
			string TmpFileName1 = FromUserName + DateTime.Now.Ticks.ToString();
			
			try
			{
				srcImg.Save("E:\\web目录\\Images\\Dest\\" + TmpFileName1 + ".png");
				imgurl = "http://www.yourweb.com/Images/Dest/" + TmpFileName1 + ".png";
			}
			catch
			{
				srcImg.Save("E:\\web目录\\Images\\Dest\\" + TmpFileName1 + ".jpg");
				imgurl = "http://www.yourweb.com/Images/Dest/" + TmpFileName1 + ".jpg";
			}
			
			guoqi.Dispose();
			srcImg.Dispose();
			graphics.Dispose();
			
			return imgurl;
		}
		
		//使用MediaId加普通access_token从微信服务器下载图片文件
		public void DownloadFileByMediaId(string FilePathAndName,string MediaId)
		{
			//获取普通access_token
			QinMingWeixinContainer wc = new QinMingWeixinContainer();
			string access_token = wc.GetAccessToken();
			
			//向微信服务器发起GET请求
			string strUrl = "https://api.weixin.qq.com/cgi-bin/media/get?access_token=" + access_token + "&media_id=" + MediaId; 
			QinMingTools.WriteLog("用mediaid从微信服务器获取图片", strUrl);    //可以到日志里用这个拼接后的url复制到浏览器或者apiPost软件中测试是否正常
			HttpWebRequest myReq = (HttpWebRequest)HttpWebRequest.Create(strUrl);
			
			//从微信服务器下载图片文件
			try
			{
				HttpWebResponse myResponse = (HttpWebResponse)myReq.GetResponse(); 
				Stream myStream = myResponse.GetResponseStream();
			    System.Drawing.Image img;
				img = System.Drawing.Image.FromStream(myStream);  
			    img.Save(FilePathAndName, System.Drawing.Imaging.ImageFormat.Jpeg); 
				img.Dispose();
				myResponse.Close();
				QinMingTools.WriteLog("用mediaid从微信服务器获取图片", "success");
			}
			catch (Exception ex) 
			{
				QinMingTools.WriteLog("用mediaid从微信服务器获取图片", ex.ToString());
			}

		}
    }
}